export class FileUpload {
    fileInput = document.createElement("input");
    formData = new FormData();

    constructor(public url: string) {
        this.fileInput.type = "file";
        this.fileInput.style.width = "0px";
        this.fileInput.style.height = "0px";
        document.body.appendChild(this.fileInput);

    }

    setFileAccept(accept: string) {
        this.fileInput.accept = accept;
    }


    static imageArr = [".jpeg", ".jpg", ".bmp", ".png"];
    static imageType = FileUpload.imageArr.join(",");

    static txtArr = [".xls", ".doc", ".txt", ".pdf"]
    static txtType = FileUpload.txtArr.join(",");

    static videoArr = [".mp4", ".mpeg", ".wmv", ".avi"];
    static videoType = FileUpload.videoArr.join(",");


    static matchSuffix(name: string, fileType: string[]) {
        let si = name.lastIndexOf(".");
        if (si > 0) {
            let sufixName = name.substring(si, name.length).toLowerCase();
            for (let s of fileType) {
                if (sufixName === s)
                    return true;
            }
        }
        return false;
    }

    onSelectFile = (res: File)=> {
    }

    /**
     * 上传进度
     */
    onProg = (ev: ProgressEvent)=> {
    }

    /**
     * 下载进度
     */
    onRespProg = (ev: ProgressEvent)=> {
    }

    upload(func: (xhr: XMLHttpRequest)=>void) {
        this.fileInput.onchange = e=> {
            let file = this.fileInput!.files![0];
            document.body.removeChild(this.fileInput);
            if (this.onSelectFile)
                this.onSelectFile(file);

            // 实例化一个AJAX对象
            var xhr = new XMLHttpRequest();
            xhr.onprogress = this.onRespProg;
            xhr.upload.onprogress = this.onProg;
            xhr.onreadystatechange = (ev) => {
                if (xhr.readyState == 4) {
                    try {
                        func(xhr)
                    } catch (e) {
                        alert(e.toString());
                    }
                }

            };
            xhr.open("POST", this.url, true);

            // 发送表单数据
            xhr.send(this.formData);
        }

        this.fileInput.click();
    }


    ///////////class end
}